package use_datasource;

import com.mysql.jdbc.jdbc2.optional.MysqlDataSource;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

public class use_datasource {
    //下面两个方法，功能都是相同的，都是连接数据库

    //11.20习得方法
    public static void getConnectionUserDriverManger() throws ClassNotFoundException, SQLException {
        //1.注册驱动
        Class.forName("com.mysql.jdbc.Driver");
        //2.获取驱动
        String url = "jdbc:mysql://127.0.0.1:3306/testbase?useSSL=false&characterEncoding=utf8";
        String user = "root";
        String password = "missh111";
        try (Connection connection = DriverManager.getConnection(url, user, password)) {
        }
    }

    //1.新版JDBC标准提供的写法
    //2.写法比url的方式更准确，不容易出现拼写错误
    //3.支持连接池方式，所以可能效率更高
    public static void getConnectionUseDatasource() throws SQLException {
        DataSource dataSource;
        MysqlDataSource mysqlDataSource=new MysqlDataSource();
        mysqlDataSource.setServerName("127.0.0.1");
        mysqlDataSource.setPort(3306);
        mysqlDataSource.setUser("root");
        mysqlDataSource.setPassword("missh111");
        mysqlDataSource.setDatabaseName("testbase");
        mysqlDataSource.setUseSSL(false);
        mysqlDataSource.setCharacterEncoding("utf8");

        //DataSource也支持url的写法
        //mysqlDataSource.setUrl( "jdbc:mysql://127.0.0.1:3306/testbase?useSSL=false&characterEncoding=utf8");

        dataSource=mysqlDataSource;//向上转型  MysqlDataSource是一个实现了dataSource接口的类

        try (Connection connection=dataSource.getConnection()){
            //获取Connection对象
        }
    }
}
